package com.lian.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lian.domain.User;
import com.lian.service.impl.UserServiceImpl;

@Controller
public class LoginController {
	@Autowired
	private UserServiceImpl service;
	
	@RequestMapping(value="/index.html")
	public String loginPage(){
		return "login";
	}
	
	@RequestMapping(value="/loginCheck.html")
	public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){
		try{
			Boolean isValidUser = service.hasMatchUsesr(loginCommand.getUserName(), loginCommand.getPassword());
			if(isValidUser){
				User user = service.findUserByUserName(loginCommand.getUserName());
				user.setLastIp(request.getLocalAddr());
				user.setLastVisit(new Date());
				service.loginSuccess(user);
				request.getSession().setAttribute("user", user);
				return new ModelAndView("main");
			}else{
				return new ModelAndView("login", "error", "用户名或密码错误!");
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
	
	
}
